import math
import datetime
import os


def humanize_bytes(x):
    x = float(x)
    if x > math.pow(2,30):
        return humanize_count(x/math.pow(2,30),'GB','GB')
    if x > math.pow(2,20):
        return humanize_count(x/math.pow(2,20),'MB','MB')
    if x > math.pow(2,10):
        return humanize_count(x/math.pow(2,10),'KB','KB')
    return humanize_count( x, 'byte', 'bytes' )

    
def humanize_timedelta(td):
    s = td.seconds
    if s<60:
        return humanize_count( s, 'second', 'seconds' )
    m = s/60.0
    if m<60:
        return humanize_count( m, 'minute', 'minutes' )
    h = m/60.0
    if h<24:
        return humanize_count( h, 'hour', 'hours' )
    d = h/24.0
    return humanize_count( d, 'day', 'days' )


def humanize_count(x, s, p, places=1):
    x = float(x)*math.pow(10, places)
    x = round(x)
    x = x/math.pow(10, places)
    if x-int(x)==0:
        x = int(x)
    if x==1:
        return str(x) +' ' + s
    else:
        return str(x) +' ' + p
    
def get_tz_offset():
    td = datetime.datetime.now() - datetime.datetime.utcnow()
    return datetime.timedelta( td.days, td.seconds + round(td.microseconds/1000000.0) )

def get_x_years_ago(d, x):
    year, month, day = d.year, d.month, d.day
    year -= x
    try:
        return d.replace(year=year, month=month)
    except ValueError:
        print 'poop'
        try:
            return d.replace(year=year, month=month, day=day-1 )
        except ValueError:
            print 'poop2'

def get_x_months_ago(d, x):
    year, month, day = d.year, d.month, d.day
    month -= x
    while month <= 0:
        year -= 1; month += 12
    try:
        return d.replace(year=year, month=month)
    except ValueError:
        print 'poop'
        try:
            return d.replace(year=year, month=month, day=day-1 )
        except ValueError:
            print 'poop2'
            try:
                return d.replace(year=year, month=month, day=day-2 )
            except ValueError:
                print 'poop3'
                try:
                    return d.replace(year=year, month=month, day=day-3 )
                except ValueError:
                    print 'poop4'

def get_x_days_ago(d, x):
    return d - datetime.timedelta(x)

def get_current_username():
    return os.environ["USER"]

